#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import json
import os

import fce_util.libs.common as common
import fce_util.libs.constants as constants
import fce_util.deploys.resource_mgr as resource
from fce_util.libs import log as loggers
from fce_util.fceres import fce_res_common


logger = loggers.g_logger.logger

def operator_create(args):
    """
    FCE Kube ray operator create entry
    """
    logger.debug('operator_create enter,args:{}'.format(args))
    kube_config = args.kube_config if args.kube_config else constants.KUBE_CONFIG_DEFAULT_PATH
    namespace = args.namespace if args.namespace else 'default'

    script_dir = constants.FCE_UTIL_HOME + "/fce_util/scripts/"
    os.chdir(script_dir)
    if not os.path.exists(constants.OPERATOR_INSTALL_SCRIPT):
        stdout = "kube ray operator install script {} not exist".format(constants.OPERATOR_INSTALL_SCRIPT)
        logger.error(stdout)
        fce_res_common(success = False, errcode = 'Deploy.OperatorInstallFailed', errmsg = stdout)
        return
    script_path = script_dir + constants.OPERATOR_INSTALL_SCRIPT
    #cmd = ". {} {} {} {} {}>> {}.log 2>&1 &".format(script_path, kube_config, namespace, args.image, constants.KUBE_OPERATOR_DIR, constants.OPERATOR_INSTALL_SCRIPT)
    cmd = "bash {} {} {} {} {}".format(script_path, kube_config, namespace, args.image, constants.KUBE_OPERATOR_DIR)
    logger.debug('cmd is : {}, script_dir is {}, pwd is {}'.format(cmd, script_dir, os.getcwd()))
    status, response = common.run_shell_with_timeout(cmd, 10)
    if status:
        stdout = "kube ray operator {} install script exec failed, exit code: {},output:{}".format(constants.KUBE_OPERATOR_NAME, status, response)
        fce_res_common(success = False, errcode = 'Deploy.OperatorInstallFailed', errmsg = stdout)
        return

    if not resource.checkServiceStatus(constants.KUBE_OPERATOR_NAME, 'op', namespace, 10, 2):
        stdout = "kube ray operator {} install failed".format(constants.KUBE_OPERATOR_NAME)
        logger.error(stdout)
        fce_res_common(success = False, errcode = 'Deploy.OperatorInstallFailed', errmsg = stdout)
        return

    msg = {'Success': True}
    msg['Message'] = {
        'Msg': 'Kube ray operator install success'
    }
    print(json.dumps(msg))

def FCE_operator_create(args):
    if args.rayc == 'operator_create':
        operator_create(args)
        return
    args.this_parser.print_help()

def make(parser):
    """
    FCE Kube ray operator check entry
    """
    parser.add_argument( 
        '--image',
        dest='image',
        nargs = '?',
        metavar = ('IMAGE'),
        help='Kube Ray Operator Image',
        required=False,
    )
    parser.add_argument( 
        '--namespace',
        dest='namespace',
        nargs = '?',
        metavar = ('NAMESPACE'),
        help='Ray Cluster Namespace',
        required=False,
    )
    
    parser.add_argument( 
        '--kube_config',
        dest='kube_config',
        nargs = '?',
        metavar = ('KUBE_CONFIG'),
        help='Kube Config File Path',
        required=False,
    )
    
    parser.set_defaults(
        func=FCE_operator_create,
        this_parser=parser
    )